﻿using Xejen.Communication.Configuration;
using Xejen.Communication.Endpoints;
using Xejen.Communication.Socket.Abstract;
using Xejen.Communication.Socket.Configuration;
using Xejen.Logger;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Xejen.Communication.Socket.Communicator
{
    /// <summary>
    /// 基于Socket协议实现的通讯器
    /// </summary>
    /// <typeparam name="TSocketInvoker"><inheritdoc cref="ISocketInvoker" path="/summary"/></typeparam>
    /// <creator>marc</creator>
    public class SocketCommunicator<TSocketInvoker> : Communicator<SocketConfig, HeartbeatConfig, Object>, ICommunicator<SocketConfig, HeartbeatConfig>, ISocketCommunicator
        where TSocketInvoker : ISocketInvoker
    {
        private readonly ILoggerManager _loggerManager;

        /// <inheritdoc/>
        public ConnectionConfig CurrentConnection { get; protected set; }

        /// <inheritdoc cref="ISocketInvokerCreator{TSocketInvoker}"/>
        protected ISocketInvokerCreator<TSocketInvoker> SocketInvokerCreator { get; }

        /// <inheritdoc/>
        protected override JsonSerializerOptions JsonSerializerOptions => Config.JsonSerializerOptions;

        /// <inheritdoc cref="SocketCommunicator{TSocketInvoker}"/>
        /// <param name="config"><inheritdoc cref="Communicator{TConfig, HeartbeatConfig, TAddress}.Config" path="/summary"/></param>
        /// <param name="socketInvokerCreator"><inheritdoc cref="SocketInvokerCreator" path="/summary"/></param>
        /// <param name="loggerManager"><inheritdoc cref="ILoggerManager" path="/summary"/></param>
        public SocketCommunicator(
            SocketConfig config,
            ISocketInvokerCreator<TSocketInvoker> socketInvokerCreator,
            ILoggerManager loggerManager) : base(config, loggerManager)
        {
            Check.NotNull(config, nameof(config));
            Check.NotNull(socketInvokerCreator, nameof(socketInvokerCreator));
            Check.NotNull(loggerManager, nameof(loggerManager));

            Config = config;
            SocketInvokerCreator = socketInvokerCreator;
            _loggerManager = loggerManager;
            Logger = _loggerManager.CreateLogger<SocketCommunicator<TSocketInvoker>>();
        }

        /// <summary>
        /// 设置当前连接配置
        /// </summary>
        /// <param name="connectionConfig"></param>
        public void SetCurrentConnection(ConnectionConfig connectionConfig)
        {
            CurrentConnection = connectionConfig;
        }

        /// <inheritdoc/>
        public virtual async Task<SocketResponse> SendAsync(byte[] input, ConnectionConfig connectionConfig = null, int timeout = -1, CancellationToken cancellationToken = default)
        {
            var config = connectionConfig ?? CurrentConnection;

            var task = SocketInvokerCreator.CreateOrGet(config).SendAsync(input, GetTimeout(timeout), cancellationToken);

            return await LogInvokeAsync(task, null, GetTimeout(timeout), input, cancellationToken);
        }

        /// <inheritdoc/>
        public virtual async Task<SocketResponse> SendAsync(string input, ConnectionConfig connectionConfig = null, int timeout = -1, CancellationToken cancellationToken = default)
        {
            var config = connectionConfig ?? CurrentConnection;

            byte[] dataBytes = config.Encoding.GetBytes(JsonSerializer.Serialize(input, Config.JsonSerializerOptions));

            var task = SocketInvokerCreator.CreateOrGet(config).SendAsync(dataBytes, GetTimeout(timeout), cancellationToken);

            return await LogInvokeAsync(task, null, GetTimeout(timeout), input, cancellationToken);
        }
    }
}
